package org.example.yuewen.solution18;

import java.util.*;

/**
 * @author: lynn
 * @Descript:  https://blog.csdn.net/weixin_42449534/article/details/100011417
 * @date: 2021/3/31 21:45
 * @version: 1.0
 */
public class SortedMapByValue {

    public static void main(String[] args) {

        Map<String, Integer> map = new TreeMap<>();
        map.put("a2", 100);map.put("b", 300);map.put("c", 200);map.put("a1", 100);
        List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>()  {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                //默认升序
                return o1.getKey().compareTo(o2.getKey());//return o2.getValue().compareTo(o1.getValue());

            }
        });
        //按value值进行排序，就是将map 转 list
        Map<String, Integer> treeMap3 = new TreeMap<>();
        treeMap3.put("a", 22222);treeMap3.put("c", 11111);treeMap3.put("b", 33333);treeMap3.put("d", 44444);
        List<Map.Entry<String, Integer>> list3 = new ArrayList<>(treeMap3.entrySet());
        Collections.sort(list3, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                //默认升序
                return o1.getValue().compareTo(o2.getValue()); //return o2.getValue().compareTo(o1.getValue());
            }
        });
        for (Map.Entry<String, Integer> m : list3) {
            System.out.println(m.getKey() + ":" + m.getValue());
        }
    }
}
